//
//  CustomEmbroidery.h
//  AmountBody
//
//
//  Created by Qiu Jishuai on 2017/8/8.

#import "CustomEmbroideryView.h"
#import "Masonry.h"
#import "CustomAttributeCell.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import "CustomAttribute.h"
#import "CustomEmbroidery.h"
#import "PopUpButton.h"

#define kCellIdentifier @"CustomAttributeCell"

@interface CustomEmbroideryView()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *addButton;
@property (weak, nonatomic) IBOutlet UIView *uploadView;
@property (weak, nonatomic) IBOutlet UIButton *uploadButton;
@property (weak, nonatomic) IBOutlet UITextField *contentTextFiled;
@property (weak, nonatomic) IBOutlet UICollectionView *topCollectionView;
@property (weak, nonatomic) IBOutlet UIView *container;
@property (weak, nonatomic) IBOutlet UICollectionView *bottomCollectionView;
@end

@implementation CustomEmbroideryView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        NSAssert(NO, @"需要通过[CustomEmbroideryView view]方法实例化");
    }
    return self;
}

+ (instancetype)view {
    CustomEmbroideryView *view = [[UINib nibWithNibName:@"CustomEmbroideryView" bundle:nil] instantiateWithOwner:nil options:nil].lastObject;
    return view;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setup];
}

- (IBAction)addButtonClicked:(id)sender {

    if (self.selectionBlock) {
        self.selectionBlock(self.customEmbroidery);
    }
    [self dismiss];
}

- (void)setContenType:(CustomEmbroideryContentType)contenType {
    _contenType = contenType;
    switch (contenType) {
        case CustomEmbroideryContentTypeDefault:
            self.uploadView.hidden = YES;
            self.contentTextFiled.hidden = NO;
            break;
        default:
            self.uploadView.hidden = NO;
            self.contentTextFiled.hidden = YES;
            break;
    }
}

- (void)setup {

    self.frame = [UIScreen mainScreen].bounds;
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    
    [self addSubview:self.container];
    self.contenType = CustomEmbroideryContentTypeDefault;

    UILabel *leftLabel = [[UILabel alloc] init];
    leftLabel.textColor = [UIColor blackColor];
    leftLabel.text = @"刺绣内容: ";
    leftLabel.font = [UIFont systemFontOfSize:14];
    [leftLabel sizeToFit];
    leftLabel.frame = CGRectMake(0, 0, leftLabel.frame.size.width, 38);
    self.contentTextFiled.borderStyle = UITextBorderStyleNone;
    self.contentTextFiled.leftView = leftLabel;
    self.contentTextFiled.leftViewMode = UITextFieldViewModeAlways;
    [self.contentTextFiled addLineOnPosition:UIViewLinePositionBottom color:[UIColor colorWithWhite:0 alpha:0.3] lineWidth:3 insets:UIEdgeInsetsMake(0, 0, -3, 0)];
    
    [self setupCollectionView:self.topCollectionView];
    [self setupCollectionView:self.bottomCollectionView];
    self.customEmbroidery = [CustomEmbroidery new];

    RAC(self.addButton, enabled) = [RACSignal
                                    combineLatest:@[RACObserve(self.customEmbroidery, front),
                                                    RACObserve(self.customEmbroidery, color)]
                                    reduce:^id (id font, id color){
                                        return @(font != nil && color != nil);
                                    }];

}

- (void)setupCollectionView: (UICollectionView *)collectionView {

    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
    [collectionView registerClass:[CustomAttributeCell class] forCellWithReuseIdentifier:kCellIdentifier];

    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(50, 50);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsZero;
}

- (void)showInView: (UIView *)view {
    if (view) {
        [view addSubview: self];
        [view bringSubviewToFront:self];
    } else {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview: self];
    }

    CGAffineTransform transform = CGAffineTransformConcat(CGAffineTransformMakeScale(0.001, 0.001), CGAffineTransformMakeTranslation(0, 50));
    self.container.transform = transform;

    [UIView animateWithDuration:0.25
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.container.transform = CGAffineTransformIdentity;
                         self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
                     }
                     completion:^(BOOL finished) {
                         if (self.contenType == CustomEmbroideryContentTypeDefault) {
                             [self.contentTextFiled becomeFirstResponder];
                         }
                     }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.25
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.container.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(0.001, 0.001), CGAffineTransformMakeTranslation(0, 50));
                         self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
                     }
                     completion:^(BOOL finished) {
                         [self removeFromSuperview];
                     }];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = touches.anyObject;
    CGPoint location = [touch locationInView:self];
    if (CGRectContainsPoint(self.container.frame, location)) {
        [super touchesEnded:touches withEvent:event];
    } else {
        if (self.contentTextFiled.isFirstResponder) {
            [self.contentTextFiled resignFirstResponder];
        } else {
            [self dismiss];
        }
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.topCollectionView) {
        return self.customEmbroidery.colorAttributes.count;
    } else {
        return self.customEmbroidery.fontAttributes.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CustomAttributeCell *cell = (CustomAttributeCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:@"xuanzekuang"];

    if (collectionView == self.topCollectionView) {
        CustomAttribute *attribute = self.customEmbroidery.colorAttributes[indexPath.item];

        RAC(cell, attributeSelected) = [[RACObserve(attribute, selected) distinctUntilChanged] takeUntil:cell.rac_prepareForReuseSignal];
    } else {
        CustomAttribute *attribute = self.customEmbroidery.fontAttributes[indexPath.item];

        RAC(cell, attributeSelected) = [[RACObserve(attribute, selected) distinctUntilChanged] takeUntil:cell.rac_prepareForReuseSignal];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    if (collectionView == self.topCollectionView) {
        CustomAttribute *attribute = self.customEmbroidery.colorAttributes[indexPath.item];
        if ([attribute isEqual:self.customEmbroidery.color]) {
            return;
        }
        attribute.selected = YES;
        self.customEmbroidery.color.selected = NO;
        self.customEmbroidery.color = attribute;

    } else {
        CustomAttribute *attribute = self.customEmbroidery.fontAttributes[indexPath.item];
        if ([attribute isEqual:self.customEmbroidery.front]) {
            return;
        }
        attribute.selected = YES;
        self.customEmbroidery.front.selected = NO;
        self.customEmbroidery.front = attribute;
    }

    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];

    PopUpButton *button = [[PopUpButton alloc] init];
    button.title = @"123213223232";
    CGRect rect = [self convertRect:cell.frame fromView:cell.superview];
    [button showFromRect:rect inView:self];
}


@end


